import { upload } from '@/apis';
import { restAdd } from '@/apis/rest';
import router from '@/router';
import { defineStore } from 'pinia';
import { Article, ArticleData, writeActions, writeGetters, writeState } from './types';
const state = (): writeState => {
    return {
        component: {
            placeholder: '第一行是文章标题噢~😄，以"# 文章名称"开头',
        },
        data: {
            lineNumber: true, // 是否显示行号
            tableShape: [12, 12], // 表格大小
            showCodeRowNumber: true, // 是否显示代码行号
        },
        form: {
            title: '',
            content: '',
            description: '不知道写点什么好~',
            images: [],
            cover: 'http://localhost:3000/public/cover.jpg',
            views: 0,
            likes: 0,
            comments: 0,
            favorites: 0,
            shares: 0,
            categories: [],
        },
        imgUrlMap: new Map(),
    }
}

const actions: writeActions = {
    async _onSave(v: string, h: Promise<string>) {
        let data = {} as Article;
        data.title = v.split('\n')[0].replace('#', '').trim();
        data.content = await h;
        data.images = [];

        const matches = data.content.match(/src="([^"]+)"/g);
        if (matches) {
            data.images = matches.map(match => decodeURIComponent(match.replace('src="', '').replace('"', '')));
        }
        data = { ...this.form, ...data }
        restAdd('article', data).then((res: ArticleData) => {
            console.log('保存成功');
            this._oninitForm();
        })
    },
    _onTip() {
        console.log('onTip');
    },
    async _onUploadImg(files, callback) {
        const res = await Promise.all(
            files.map((file) => {
                return new Promise((rev, rej) => {
                    const form = new FormData();
                    form.append('file', file);
                    form.append('name', file.name);
                    form.append('size', file.size.toString());
                    form.append('type', file.type);
                    form.append('page', router.currentRoute.value.path);
                    upload(form).then((res: ArticleData) => {
                        this.imgUrlMap.set(res.url, res.id)
                        rev(res);
                    }).catch((error) => rej(error));
                });
            })
        );

        callback(res.map((item: ArticleData) => item.url));
    },
    _oninitForm() {
        this.form = {
            title: '',
            content: '',
            description: '不知道写点什么好~',
            images: [],
            cover: 'http://localhost:3000/public/cover.jpg',
            views: 0,
            likes: 0,
            comments: 0,
            favorites: 0,
            shares: 0,
            categories: [],
        }
        this.imgUrlMap.clear();
    }
}

const getters: writeGetters = {
}


export const useWriteStore = defineStore('writeComponet', {
    state,
    actions,
    getters,
});

